package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.res.LoginRespVo;
import com.itheima.stock.vo.res.ResponseCode;
import com.itheima.stock.vo.res.R;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        if(vo==null|| Strings.isNullOrEmpty(vo.getUsername())||Strings.isNullOrEmpty(vo.getPassword())||Strings.isNullOrEmpty(vo.getCode())){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        String code=(String)redisTemplate.opsForValue().get("ck:"+vo.getRkey());


        if(!code.equals(vo.getCode())||Strings.isNullOrEmpty(code)){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
         redisTemplate.delete("ck"+vo.getRkey());

        SysUser sysUser=sysUserMapper.findByUsername(vo.getUsername());

        if(sysUser==null||!passwordEncoder.matches(vo.getPassword(),sysUser.getPassword())){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        LoginRespVo loginRespVo=new LoginRespVo();
        BeanUtils.copyProperties(sysUser,loginRespVo);
        return R.ok(loginRespVo);

    }

    @Override
    public R<Map> generateCode() {
        long idSession = idWorker.nextId();
        String code = RandomStringUtils.randomNumeric(4);
        redisTemplate.opsForValue().set("ck:"+idSession,code,60, TimeUnit.SECONDS);
        Map<String,String> map=new HashMap<>();
        map.put("code",code);
        map.put("rkey",idSession+"");
        return R.ok(map);
    }
}
